'use strict';

var nunjucks = require('nunjucks');

function createEnv(path, opts) {
    opts=opts || {}
    var loaderOptions = {
        watch: opts.watch || true,
        noCache: opts.noCache || true
    }

    var envOptions = {
        autoescape: opts.autoescape || true,
        throwOnUndefined: opts.throwOnUndefined || false
    }

    var loader = new nunjucks.FileSystemLoader('views', loaderOptions);

    var env = new nunjucks.Environment(loader, envOptions);

    if(opts.filters){
        for(var f in opts.filters){
            env.addFilter(f,opts.filters[f]);
        }
    }

    return env;
}


module.exports=async (ctx,next)=>{
    ctx.render=function(view,model){
        var env=createEnv();
        ctx.body=env.render(view,model);
    }
    await next();
}